import React, { useEffect, useState } from "react";
import Button from "../Button";
import Panel from "./Panel";
import Spin from "../Spin";
import RcDrawer from "rc-drawer";
import useStyles from "./styles";
import type { DrawerPanelProps } from "./type";

/**
 * 参考 https://drawer-react-component.vercel.app/demo/change
 */

export default function Drawer({
  open,
  width = "640px",
  title,
  className,
  style,
  confirmDisabled,
  confimLoading = false,
  children,
  footer,
  maskClosable,
  showClose = true,
  showConfirm = true,
  extraButtons,
  lazyLoad,
  onClose,
  onConfirm,
}: DrawerPanelProps) {
  const classes = useStyles();
  const [openedOnce, setOpenedOnce] = useState(false);

  useEffect(() => {
    if (open && !openedOnce) setOpenedOnce(true);
  }, [open]);

  const footerNode = footer || (
    <div className={classes.footer}>
      {showClose && <Button onClick={onClose}>取消</Button>}
      {extraButtons?.map((i, index) => (
        <Button type="blue" key={index} onClick={i.onClick}>
          {i.text}
        </Button>
      ))}
      {showConfirm &&
        (confimLoading ? (
          <Spin></Spin>
        ) : (
          <Button type="blue" onClick={onConfirm} disabled={confirmDisabled}>
            确定
          </Button>
        ))}
    </div>
  );

  const LazyComponent = lazyLoad;

  return (
    <RcDrawer
      maskClosable={maskClosable}
      level={null}
      prefixCls="drawer-panel"
      width={width}
      style={style}
      className={className}
      open={open}
      placement="right"
      onClose={onClose}
    >
      <div className={classes.layout}>
        <div className={classes.layoutContent}>
          <Panel title={title} onClose={onClose}>
            {children}
            {openedOnce && LazyComponent && <LazyComponent />}
          </Panel>
        </div>
        <div className={classes.layoutFooter}>{footerNode}</div>
      </div>
    </RcDrawer>
  );
}
